const router = require('koa-router')()
const userService = require('../controllers/mySqlConfig')
const utils = require('../controllers/utils')

router.prefix('/bottle')

//获取文章详情
router.get('/findDetailById', async (ctx, next) => {
  console.log(ctx.request.query);
  let _id = ctx.request.query.id
  let _userId = ctx.request.query.userId
  var l = ctx.request.query.length
 async function get(_id, _userId, l){
   await userService.findDetailById(_id, _userId)
    .then(res => {
      // console.log(res);
      if (res.length !== 0) {
        console.log(res);
        ctx.body = {
          code: 200,
          mess: '查找成功',
          data: res
        }
      }
      else {
        let x = 1, id = Math.floor(Math.random()*(l-x+1)+x)
        get(id, _userId, l)
      }
    })
  }
 await get(_id, _userId, l) 
})

//获取表长度
router.get('/findNum', async (ctx, next) => {
  const data = await userService.findNum()
  // console.log(data[0]['count(msg_id)']);
  let id = data[0]['count(msg_id)']
    ctx.body = {
      code: 200,
      data: id
    }
})
//发布文章
router.post('/publish', async (ctx, next) => {
  let { title, content, user_id } = ctx.request.body
  // console.log(title, content, user_id);
  await userService.insertNote([user_id, title, content])
  .then(res => {
    if (res.affectedRows !== 0) {
      ctx.body = {
        code: 200,
        data: 'ok',
        mess: '发表成功'
      }
    } else {
      ctx.body = {
        code: 80004,
        data: 'error',
        mess: '发表失败'
      }
    }
  })
})
//消息记录
router.get('/findNewsUserid', async (ctx, next) => {
  console.log(ctx.request, '--------');
  let id = ctx.request.query.newsuserid
  await userService.findNewsUserid(id).then(res => {
      if (res.length !== 0) {
          console.log(res,'000000000');
          ctx.body = {
              code: 200,
              mess: '查找成功',
              data: res
          }
          return
      }
  }).catch(err => {
      ctx.body = {
          code: '40001',
          data: err
      }
  })
})

module.exports = router